package com.woniu.tmsvehicle.utils;


import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Component
public class SmsUtil {

    /**
     * 定义accessKeyId和secret
     * */
    public static final String ACCESS_KEY_ID = "LTAI5t7fEyqSwjYv3UPMtDdH";
    public static final String SECRET = "oQDQx1xJrNGmcUUduajhJxnxO6TsI9";

    /**
     * 获取四位数的验证码
     * */
    public String getFourNum(){
        Random random = new Random();
        int fourNum = random.nextInt(9000) + 1000;
        return String.valueOf(fourNum);
    }
    /**
     * 发送短信
     * */
    public void sendSms(String phoneNum){
        String fourNum = getFourNum();
        DefaultProfile profile = DefaultProfile.getProfile("default", ACCESS_KEY_ID, SECRET);
        //用profile创建一个client
        DefaultAcsClient client = new DefaultAcsClient(profile);

        //设置固定参数
        CommonRequest request = new CommonRequest();
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.setSysMethod(MethodType.POST);

        //设置发送相关参数
        request.putQueryParameter("PhoneNumbers", phoneNum);
        request.putQueryParameter("SignName", "京东快递");
        request.putQueryParameter("TemplateCode", "SMS_472740090");

        Map<String,String> map = new HashMap<>();
        map.put("code",fourNum);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getHttpResponse().isSuccess());
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}
